package com.aricwang.easyprofile.place;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Window;
import android.view.WindowManager;

import com.aricwang.easyprofile.R;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.OverlayItem;

public class MyItemizedOverlay extends ItemizedOverlay {
	private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
	private MapActivity mActivity;
	
	public MyItemizedOverlay(Drawable defaultMarker) {
		// important to call boundCenterBottom on the marker, otherwise, won't draw.
		super(boundCenterBottom(defaultMarker));
	}
	
	public MyItemizedOverlay(Drawable defaultMarker, Context context) {
		// important to call boundCenterBottom on the marker, otherwise, won't draw.
		super(boundCenterBottom(defaultMarker));
		mActivity = (MapActivity)context;
	}
	
	public boolean onTap(int index) {
		  showLocationDetailDialog(index);
		  return true;
		}
	
	public void addOverlay(OverlayItem overlay) {
	    mOverlays.add(overlay);
	    populate();
	}

	@Override
	protected OverlayItem createItem(int i) {
		return mOverlays.get(i);
	}

	@Override
	public int size() {
		return mOverlays.size();
	}

	
	private void showLocationDetailDialog(int index) {
		  final OverlayItem item = mOverlays.get(index);
		  AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
//		  builder.setTitle(item.getTitle());
		  builder.setMessage(item.getSnippet());
	      builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	dialog.dismiss();
	            	MyItemizedOverlay.this.selectItem(item);
	            }
	        });
	      builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	dialog.cancel();
	            }
	        });

	      AlertDialog dialog = builder.create();
	      dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	      WindowManager.LayoutParams wmlp = dialog.getWindow().getAttributes();
//	      wmlp.x = 200;
	      wmlp.y = 200;
	      
	      dialog.getWindow().setAttributes(wmlp);
		  dialog.show();
	}
	
	private void selectItem(OverlayItem item) {
		Intent data = new Intent();
		data.putExtra("Address", item.getSnippet());
		data.putExtra("Latitude", item.getPoint().getLatitudeE6()/1E6);
		data.putExtra("Longitude", item.getPoint().getLongitudeE6()/1E6);
		
		mActivity.setResult(Activity.RESULT_OK, data);
		mActivity.finish();
	}
}
